import http from 'poros/http';
import { clearLoginInfo, jumpLogin } from '@/utils/login';

import { Message } from 'element-ui';

const successCode = [0, '0'];

http.interceptors.request.use(config => {
  if (
    process.env.NODE_ENV === 'development' &&
    !config.url.includes('/api/salesforecast-service/planProcess/getJwt') &&
    !config.url.includes('/api/poros-authcenter/secret/') &&
    !config.url.includes('/api/poros-authcenter/login')
  ) {
    config.headers['poros-current-user'] = localStorage.getItem(
      'poros-current-user'
    );
  }
  return config;
});

/** 添加响应拦截器 */
http.interceptors.response.use(
  res => {
    const { code, msg } = res.data;
    const hasInterceptors = res.config.hasInterceptors;
    if (hasInterceptors) {
      const filename = res.headers['content-disposition']
        ?.split(';')
        .find(item => item.startsWith('filename'));
      const name = decodeURIComponent(
        filename?.split('=') && filename?.split('=')[1]
      );
      res.filename = name;
      return res;
    }
    if (hasInterceptors && code === 400) {
      return;
    }
    if (successCode.includes(code)) {
      return res;
    } else if (code === 401) {
      clearLoginInfo();
      jumpLogin();
      return Promise.reject(msg);
    } else {
      Message.error(msg);
      return Promise.reject(msg);
    }
  },
  err => {
    Message.error(err.response?.data?.msg || '系统异常！');
  }
);
